﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jobping.StickyBeak.Config;
using System.Web;

namespace Jobping.StickyBeak.UI
{
	public class HomeVD
	{
		public IEnumerable<RequestLog> Results { get; set; }

		public IEnumerable<string> Pages { get; set; }

		public string SelectedPage { get; set; }

		public bool Enabled { get; set; }
	}

	
	public class HomeController : IHttpHandler
	{
		private static StickyBeakConfiguration config = StickyBeakConfiguration.Current();

		ILogRepository repository;

		public HomeController()
		{
			this.repository = config.GetRepository();
		}

		public object Get(string pageName, string toggle)
		{
			var vd = new HomeVD();
			vd.Pages = this.repository.GetPages().ToList();
			

			if (String.IsNullOrEmpty(pageName))
				pageName = vd.Pages.FirstOrDefault();

			if (toggle != null)
			{
				config.Enabled = !config.Enabled;
			}
			vd.Enabled = config.Enabled;

			if (pageName == null)
				return new HomeHtml(vd);
			
			vd.SelectedPage = pageName;
			vd.Results = this.repository.GetPage(pageName).ToList();

			return new HomeHtml(vd);
		}

		public bool IsReusable
		{
			get { throw new NotImplementedException(); }
		}

		public void ProcessRequest(HttpContext context)
		{
			string pageName = context.Request.QueryString["pageName"];
			string toggle = context.Request.QueryString["toggle"];
			var result = this.Get(pageName, toggle);

			context.Response.Write(result.ToString());
		}
	}
}
